import { useCallback } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import { message } from 'antd';
import { RootState } from '../store';
import { logout, setToken, setUser } from '../store/slices/auth';
import { setMenus } from '../store/slices/menu';
import api from '../services';

/**
 * 自定义认证Hook，提供登录、登出和认证状态管理
 */
const useAuth = () => {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const { token, user, isLoggedIn } = useSelector((state: RootState) => state.auth);

  /**
   * 登录函数
   * @param phone 用户名
   * @param password 密码
   */
  const login = useCallback(
    async (phone: string, password: string) => {
      try {
        const res = await api.login({
          phone: phone,
          password: password
        });

        if (res.code === 0) {
          // 保存token和用户信息
          dispatch(setToken(res.data.access_token));
          dispatch(setUser(res.data.userInfo || {}));
          dispatch(setMenus(res.data.nav));

          // 保存到localStorage
          localStorage.setItem('menus', JSON.stringify(res.data.nav));

          message.success('登录成功！');
          navigate('/home');
          return true;
        } else {
          message.error(res.msg || '登录失败');
          return false;
        }
      } catch (error) {
        console.error('Login error:', error);
        message.error('登录异常，请稍后重试');
        return false;
      }
    },
    [dispatch, navigate]
  );

  /**
   * 登出函数
   */
  const logoutUser = useCallback(() => {
    dispatch(logout());
    navigate('/login');
    message.success('已退出登录');
  }, [dispatch, navigate]);

  return {
    token,
    user,
    isLoggedIn,
    login,
    logout: logoutUser
  };
};

export default useAuth; 